#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        if (matrix.size() == 0 || matrix[0].size() == 0) {
            return {};
        }
        int left = 0;
        int top = 0;
        int right = matrix[0].size() - 1;
        int bottom = matrix.size() - 1;
        vector<int> ans;
        while (true) {
            for (int i = left; i <= right; i++) {
                ans.emplace_back(matrix[top][i]);
            }
            top++;
            if (top > bottom) {
                break;
            }
            for (int i = top; i <= bottom; i++) {
                ans.emplace_back(matrix[i][right]);
            }
            right--;
            if (right < left) {
                break;
            }
            for (int i = right; i >= left; i--) {
                ans.emplace_back(matrix[bottom][i]);
            }
            bottom--;
            if (top > bottom) {
                break;
            }
            for (int i = bottom; i >= top; i--) {
                ans.emplace_back(matrix[i][left]);
            }
            left++;
            if (left > right) {
                break;
            }
        }
        return ans;
    }
};

int main() {
    vector<vector<int>> input = {{1 , 2, 3}, {4, 5, 6}, {7, 8, 9}};
    Solution solution;
    solution.spiralOrder(input);
    return 0;
}